package com.tbit.main.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.tbit.main.constant.AccountConfigExtConstant;
import com.tbit.main.constant.MachineFunctionConstant;
import com.tbit.main.constant.RedisConstant;
import com.tbit.main.dao.core.AccountConfigDao;
import com.tbit.main.dao.core.GeoDao;
import com.tbit.main.dao.core.MachineDao;
import com.tbit.main.exception.BaseException;
import com.tbit.main.h2.pojo.ParkPoint;
import com.tbit.main.pojo.*;
import com.tbit.main.service.*;
import com.tbit.main.util.*;
import com.tbit.manager.api.AccountDayStatApi;
import com.tbit.manager.api.dto.OperationalDataDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;


@Slf4j
@Service("dataService")
public class DataServiceImpl implements DataService {

    @Autowired
    private AccountConfigDao accountConfigDao;
    @Autowired
    private MachineDao machineDao;
    @Autowired
    private GeoDao geoDao;
    @Autowired
    private AccountSmsModelService accountSmsModelService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private MachineStatusService machineStatusService;
    @Autowired
    private GeoreGionService georeGionService;
    @Autowired
    private WorkOrderConfigService workOrderConfigService;
    @Autowired
    private AddCountFeeService addCountFeeService;
    @Autowired
    private AccountUserWorkConfigService accountUserWorkConfigService;
    @Autowired
    private AccountUserLastPosService accountUserLastPosService;
    @Autowired
    private GeoreMachineService georeMachineService;
    @Autowired
    private AccountUserConfigService accountUserConfigService;
    @Autowired
    private AccountUserService accountUserService;
    @Autowired
    private AccountConfigExtService accountConfigExtService;
    @Autowired
    private ParkPointBoundService parkPointBoundService;
    @Autowired
    private ParkPointService parkPointService;
    @Autowired
    private MachineFunctionService machineFunctionService;
    @Autowired
    private DispatchConfigService dispatchConfigService;
    @Autowired
    private BatteryService batteryService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private BatteryModelChartService batteryModelChartService;
    @Autowired
    private MachineService machineService;
    @Autowired
    private BmsBatchService bmsBatchService;
    @Autowired
    private RoleConfigService roleConfigService;
    @Autowired
    private AccountUserWorkService accountUserWorkService;
    @Autowired
    private MannedService mannedService;
    @Autowired
    private AccountDayStatApi accountDayStatApi;


    /** 只读缓存集合（全量缓存）*/
    /**
     * 设备编号-id
     */
    private volatile Map<String, Integer> machineNoId = new HashMap<>();
    /**
     * 车辆编号-设备编号
     */
    private volatile Map<String, String> machineUserNO = new HashMap<>();
    /**
     * 车辆id-车辆状态
     */
    private volatile Map<Integer, MachineStatus> machineStatusMap = new HashMap<>();
    /**
     * 车辆id-车辆信息
     */
    private volatile Map<Integer, Machine> machineMap = new HashMap<>();
    /**
     * 车辆id：分区id
     */
    private volatile Map<Integer, Integer> machineIdRegionIdMap = new HashMap<>();
    /**
     * 车辆功能
     */
    private volatile List<Integer> machineFunctionList = new ArrayList<>();
    /**
     * 车辆id-载人设备id
     */
    private volatile Map<Integer, Integer> machineMannedId = new HashMap<>();

    /**
     * 区域id-配置文件信息
     */
    private volatile Map<Integer, AccountConfig> accountConfigMap = new HashMap<>();
    /**
     * 区域id-工单配置
     */
    private volatile Map<Integer, WorkOrderConfig> workOrderConfigMap = new HashMap<>();
    /**
     * 区域id-人员工单配置
     */
    private volatile Map<Integer, List<AccountUserWorkConfig>> accountUserWorkConfigMap = new HashMap<>();
    /**
     * 运维人员 Id - 运维人员打卡
     */
    private volatile Map<Integer, AccountUserWork> accountUserWorkMap = new HashMap<>();
    /**
     * 区域id-区域围栏
     */
    private volatile Map<Integer, List<Point>> geoMap = new HashMap<>();
    /**
     * 区域id-分区id
     */
    private volatile Map<Integer, List<Integer>> accountGeoreMap = new HashMap<>();
    /**
     * 区域id-计费规则
     */
    private volatile Map<Integer, AddCountFee> accountFeeMap = new HashMap<>();
    /**
     * 区域id：调度配置
     */
    private volatile Map<Integer, DispatchConfig> accountDispatchMap = new HashMap<>();
    /**
     * 区域id-品牌
     */
    private volatile Map<Integer, Integer> accountIdMap = new HashMap<>();
    /**
     * 区域id+参数名
     */
    private volatile Map<String, AccountConfigExt> accountConfigExtMap = new HashMap<>();

    /**
     * 人员id：最后定位
     */
    private volatile Map<Integer, AccountUserLastPos> accountUserLastPosMap = new HashMap<>();
    /**
     * 人员id：人员语音
     */
    private volatile Map<Integer, AccountUserConfig> accountUserConfigMap = new HashMap<>();
    /**
     * 人员id：人员
     */
    private volatile Map<Integer, AccountUser> accountUserMap = new HashMap<>();

    /**
     * 电池NO：电池id
     */
    private volatile Map<String, Integer> batteryIdMap = new HashMap<>();
    /**
     * 电池NO：区域id
     */
    private volatile Map<String, Integer> batteryAccountIdMap = new HashMap<>();
    /**
     * 电池NO：电池型号id
     */
    private volatile Map<String, Integer> batteryModelIdMap = new HashMap<>();
    /**
     * 电池型号id：电池型号
     */
    private volatile Map<Integer, BatteryModelChart> batteryModelChartHashMap = new HashMap<>();
    /**
     * bms电池批次号id：电池批次
     */
    private volatile Map<Integer, BmsBatch> bmsBatchHashMap = new HashMap<>();

    /**
     * 分区id：人员id
     */
    private volatile Map<Integer, List<Integer>> regionIdAccountUserIdMap = new HashMap<>();
    /**
     * 分区id-分区围栏
     */
    private volatile Map<Integer, List<Point>> georeGionMap = new HashMap<>();

    /**
     * 短信配置
     */
    private volatile Map<String, AccountSmsModel> smsModelMap = new HashMap<>();

    /**
     * rfid站点id
     */
    private volatile Set<Integer> parkBoundMap = new HashSet<>();

    /**
     * 站点id: 站点信息
     */
    private volatile Map<Integer, ParkPoint> integerParkPointMap = new HashMap<>();

    /**
     * 角色id+开关名称：配置
     */
    private volatile Map<String, Integer> roleConfigMap = new HashMap<>();

    /**
     * 品牌id：资金数据
     */
    private volatile Map<Integer, Map<String, Object>> operationalDataToMainMap = new HashMap<>();

    @Override
    @PostConstruct
    @Scheduled(cron = "0 1/5 * * * ?")
    public void reloadData() {
        Long s = System.currentTimeMillis();
        try {
            Map<String, Integer> machineNoIdTemp = new HashMap<>();
            Map<String, String> machineUserNOTemp = new HashMap<>();
            Map<Integer, AccountConfig> accountConfigMapTemp = new HashMap<>();
            Map<Integer, WorkOrderConfig> workOrderConfigMapTemp = new HashMap<>();
            Map<Integer, List<AccountUserWorkConfig>> accountUserWorkConfigMapTemp = new HashMap<>();
            Map<Integer, List<Point>> geoMapTemp = new HashMap<>();
            Map<Integer, List<Integer>> accountGeoreMapTemp = new HashMap<>();
            Map<Integer, AddCountFee> accountFeeMapTemp = new HashMap<>();
            Map<Integer, List<Point>> georeGionMapTemp = new HashMap<>();
            Map<String, AccountSmsModel> accountSmsMapTemp = new HashMap<>();
            Map<Integer, Integer> accountIdMapTemp = new HashMap<>();
            Map<Integer, Machine> machineMapTemp = new HashMap<>();
            Map<Integer, AccountUserLastPos> accountUserLastPosMapTemp = new HashMap<>();
            Map<Integer, Integer> machineIdRegionIdMapTemp = new HashMap<>();
            Map<Integer, List<Integer>> regionIdAccountUserIdMapTemp = new HashMap<>();
            Map<Integer, AccountUserConfig> accountUserConfigMapTemp = new HashMap<>();
            Map<Integer, AccountUser> accountUserMapTemp = new HashMap<>();
            Map<String, AccountConfigExt> accountConfigExtMapTemp = new HashMap<>();
            Set<Integer> parkBoundMapTemp;
            Map<Integer, DispatchConfig> accountDispatchMapTemp = new HashMap<>();
            Map<Integer, String> batteryNOMapTemp = new HashMap<>();
            Map<String, Integer> batteryIdMapTemp = new HashMap<>();
            Map<String, Integer> batteryAccountIdMapTemp = new HashMap<>();
            Map<Integer, BatteryModelChart> batteryModelChartHashMapTemp = new HashMap<>();
            Map<Integer, BmsBatch> bmsBatchHashMapTemp = new HashMap<>();
            Map<String, Integer> batteryModelIdMapTemp = new HashMap<>();
            Map<String, Integer> roleConfigMapTemp = new HashMap<>();
            Map<Integer, ParkPoint> integerParkPointMapTemp = new HashMap<>();
            Map<Integer, Integer> machineMannedIdTemp = new HashMap<>();

            /**设备编号：车辆id*/
            /**车辆id：车辆信息*/
            List<Machine> machineList = machineDao.getAll();
            for (Machine machine : machineList) {
                try {
                    machineNoIdTemp.put(machine.getMachineNO(), machine.getMachineId());
                    machineMapTemp.put(machine.getMachineId(), machine);
                    machineUserNOTemp.put(machine.getUserCode(), machine.getMachineNO());
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
            /**区域id：区域配置文件信息*/
            List<AccountConfig> accountConfigs = accountConfigDao.getAll();
            for (AccountConfig accountConfig : accountConfigs) {
                try {
                    accountConfigMapTemp.put(accountConfig.getAccountId(), accountConfig);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
            /**区域id：区域工单配置信息*/
            List<WorkOrderConfig> workOrderConfigs = workOrderConfigService.getAll();
            for (WorkOrderConfig workOrderConfig : workOrderConfigs) {
                try {
                    workOrderConfigMapTemp.put(workOrderConfig.getAccountId(), workOrderConfig);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
            /**区域id：人员配置信息*/
            List<AccountUserWorkConfig> accountUserWorkConfigs = accountUserWorkConfigService.getAll();
            for (AccountUserWorkConfig accountUserWorkConfig : accountUserWorkConfigs) {
                try {
                    if (accountUserWorkConfigMapTemp.containsKey(accountUserWorkConfig.getAccountId())) {
                        accountUserWorkConfigMapTemp.get(accountUserWorkConfig.getAccountId()).add(accountUserWorkConfig);
                    } else {
                        List<AccountUserWorkConfig> accountUserWorkConfigList = new LinkedList<>();
                        accountUserWorkConfigList.add(accountUserWorkConfig);
                        accountUserWorkConfigMapTemp.put(accountUserWorkConfig.getAccountId(), accountUserWorkConfigList);
                    }
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
            /**区域id：区域计费规则*/
            List<AddCountFee> addCountFees = addCountFeeService.getAll();
            for (AddCountFee addCountFee : addCountFees) {
                try {
                    accountFeeMapTemp.put(addCountFee.getAccountId(), addCountFee);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
            /**区域id：围栏数据*/
            List<Geo> geos = geoDao.getByAll();
            for (Geo geo : geos) {
                try {
                    if (geo.getPoints() != null) {
                        geoMapTemp.put(geo.getAccountId(), GeoUtil.getPoints(geo.getPoints()));
                    }
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }

            /**区域id:分区id*/
            List<GeoreGion> georeGions = georeGionService.getAll();
            for (GeoreGion georeGion : georeGions) {
                try {
                    georeGionMapTemp.put(georeGion.getRegionId(), GeoUtil.getPoints(georeGion.getPoints()));
                    if (accountGeoreMapTemp.containsKey(georeGion.getAccountId())) {
                        accountGeoreMapTemp.get(georeGion.getAccountId()).add(georeGion.getRegionId());
                    } else {
                        List<Integer> regionIds = new LinkedList<>();
                        regionIds.add(georeGion.getRegionId());
                        accountGeoreMapTemp.put(georeGion.getAccountId(), regionIds);
                    }
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }

            /**品牌id_短信类型：短信配置*/
            List<AccountSmsModel> accountSmsModels = accountSmsModelService.getSmsModelByAll();
            for (AccountSmsModel accountSmsModel : accountSmsModels) {
                try {
                    accountSmsMapTemp.put(accountSmsModel.getAccountId() + ":" + accountSmsModel.getSmsType(), accountSmsModel);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
            /**区域id-品牌id*/
            List<Map<String, Object>> accountId = accountService.getAccountAll();
            for (Map<String, Object> stringObjectMap : accountId) {
                try {
                    accountIdMapTemp.put(Integer.parseInt(stringObjectMap.get("accountId").toString()), Integer.parseInt(stringObjectMap.get("parentId").toString()));
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }

            /**人员id:人员最后位置*/
            List<AccountUserLastPos> accountUserLastPosList = accountUserLastPosService.getAll();
            for (AccountUserLastPos accountUserLastPos : accountUserLastPosList) {
                accountUserLastPosMapTemp.put(accountUserLastPos.getAccountUserId(), accountUserLastPos);
            }

            /**车辆id：分区id*/
            List<Map<String, Object>> regionIdMachineIdList = georeMachineService.getAll();
            for (Map<String, Object> map : regionIdMachineIdList) {
                machineIdRegionIdMapTemp.put(Integer.parseInt(map.get("machineId").toString()), Integer.parseInt(map.get("regionId").toString()));
            }

            /**分区id:人员id*/
            List<Map<String, Object>> accountUserRegionId = georeGionService.getBoundAll();
            for (Map<String, Object> map : accountUserRegionId) {
                if (regionIdAccountUserIdMapTemp.containsKey(Integer.parseInt(map.get("regionId").toString()))) {
                    regionIdAccountUserIdMapTemp.get(Integer.parseInt(map.get("regionId").toString())).add(Integer.parseInt(map.get("accountUserId").toString()));
                } else {
                    List<Integer> integerList = new LinkedList<>();
                    integerList.add(Integer.parseInt(map.get("accountUserId").toString()));
                    regionIdAccountUserIdMapTemp.put(Integer.parseInt(map.get("regionId").toString()), integerList);
                }
            }

            /**人员id:语音配置*/
            List<AccountUserConfig> accountUserConfigs = accountUserConfigService.getAll();
            for (AccountUserConfig accountUserConfig : accountUserConfigs) {
                accountUserConfigMapTemp.put(accountUserConfig.getAccountUserId(), accountUserConfig);
            }

            /**人员id:人员*/
            List<AccountUser> accountUsers = accountUserService.getAll();
            for (AccountUser accountUser : accountUsers) {
                accountUserMapTemp.put(accountUser.getAccountUserId(), accountUser);
            }

            /**区域参数扩展配置*/
            List<AccountConfigExt> accountConfigExts = accountConfigExtService.getAll();
            for (AccountConfigExt accountConfigExt : accountConfigExts) {
                accountConfigExtMapTemp.put(accountConfigExt.getAccountId() + accountConfigExt.getParamKey(), accountConfigExt);
            }

            /**rfid站点*/
            parkBoundMapTemp = parkPointBoundService.getByParkPointIdAll();

            /**站点：站点信息*/
            List<ParkPoint> parkPoints = parkPointService.getAll();
            List<AccountConfigExt> accountConfigExtList = accountConfigExtService.getAll();
            Map<Integer, String> allowRangeConfigMap = accountConfigExtList.stream()
                    .filter(item -> Objects.equals(item.getParamKey(), AccountConfigExtConstant.ALL_PARK_POINT_ALLOW_RANGE))
                    .collect(Collectors.toMap(AccountConfigExt::getAccountId, item -> item.getParamValue()));
            for (ParkPoint parkPoint : parkPoints) {
                try {
                    if (parkPoint.getAllowRange() == -1){
                        String allowRangeConfig = allowRangeConfigMap.get(parkPoint.getAccountId());
                        if (!StringUtils.isEmpty(allowRangeConfig)){
                            parkPoint.setAllowRange(Integer.valueOf(allowRangeConfig));
                        }else {
                            parkPoint.setAllowRange(20);
                        }
                    }
                    if (parkPoint.getAllowRange() < 10) {
                        parkPoint.setAllowRange(10);
                    }
                    integerParkPointMapTemp.put(parkPoint.getParkPointId(), parkPoint);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }

            /**车辆功能*/
            List<Integer> machineType = new LinkedList<>();
            machineType.add(MachineFunctionConstant.MACHINE_TYPE_HELMAT);
            machineType.add(MachineFunctionConstant.MACHINE_TYPE_ZNTKS);
            machineType.add(MachineFunctionConstant.MACHINE_TYPE_LYTKS);
            machineFunctionList = machineFunctionService.getType(machineType);

            /**区域id：调度配置*/
            List<DispatchConfig> dispatchConfigList = dispatchConfigService.getAll();
            for (DispatchConfig dispatchConfig : dispatchConfigList) {
                accountDispatchMapTemp.put(dispatchConfig.getAccountId(), dispatchConfig);
            }

            /**电池id：电池编号*/
            /**电池no：电池id*/
            /**电池no：型号id*/
            List<Battery> batteryList = batteryService.getAll();
            for (Battery battery : batteryList) {
                batteryIdMapTemp.put(battery.getBatteryNO(), battery.getBatteryId());
                batteryNOMapTemp.put(battery.getBatteryId(), battery.getBatteryNO());
                batteryAccountIdMapTemp.put(battery.getBatteryNO(), battery.getAccountId());
                batteryModelIdMapTemp.put(battery.getBatteryNO(), battery.getBatteryModelId());
            }
            List<BatteryModelChart> batteryModelCharts = batteryModelChartService.getAll();
            for (BatteryModelChart batteryModelChart : batteryModelCharts) {
                batteryModelChartHashMapTemp.put(batteryModelChart.getBatteryModelId(), batteryModelChart);
                redisService.add(RedisConstant.PUSH_BMS_Model + batteryModelChart.getBatteryModelId(), JSONObject.toJSONString(batteryModelChart));
            }

            /**bms电池批次号：电池批次*/
            List<BmsBatch> bmsBatches = bmsBatchService.getAll();
            for (BmsBatch bmsBatch : bmsBatches) {
                bmsBatchHashMapTemp.put(bmsBatch.getBatch(), bmsBatch);
            }

            /**角色id+开关名称：配置*/
            List<RoleConfig> roleConfigs = roleConfigService.getAll();
            for (RoleConfig roleConfig : roleConfigs) {
                roleConfigMapTemp.put(roleConfig.getRoleId() + roleConfig.getParamKey(), roleConfig.getParamValue());
            }

            try {
                List<Manned> mannedList = mannedService.getAll();
                for (Manned manned : mannedList) {
                    machineMannedIdTemp.put(manned.getMachineId(), manned.getMannedId());
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }

            List<AccountUserWork> accountUserWorkList = accountUserWorkService.getList();
            accountUserWorkMap = accountUserWorkList.stream().collect(Collectors.toMap(AccountUserWork::getAccountUserId, Function.identity()));

            machineNoId = machineNoIdTemp;
            machineUserNO = machineUserNOTemp;
            accountConfigMap = accountConfigMapTemp;
            workOrderConfigMap = workOrderConfigMapTemp;
            accountUserWorkConfigMap = accountUserWorkConfigMapTemp;
            geoMap = geoMapTemp;
            georeGionMap = georeGionMapTemp;
            accountGeoreMap = accountGeoreMapTemp;
            accountFeeMap = accountFeeMapTemp;
            smsModelMap = accountSmsMapTemp;
            accountIdMap = accountIdMapTemp;
            machineMap = machineMapTemp;
            accountUserLastPosMap = accountUserLastPosMapTemp;
            machineIdRegionIdMap = machineIdRegionIdMapTemp;
            regionIdAccountUserIdMap = regionIdAccountUserIdMapTemp;
            accountUserConfigMap = accountUserConfigMapTemp;
            accountUserMap = accountUserMapTemp;
            accountConfigExtMap = accountConfigExtMapTemp;
            parkBoundMap = parkBoundMapTemp;
            accountDispatchMap = accountDispatchMapTemp;
            batteryIdMap = batteryIdMapTemp;
            batteryAccountIdMap = batteryAccountIdMapTemp;
            batteryModelChartHashMap = batteryModelChartHashMapTemp;
            bmsBatchHashMap = bmsBatchHashMapTemp;
            batteryModelIdMap = batteryModelIdMapTemp;
            roleConfigMap = roleConfigMapTemp;
            integerParkPointMap = integerParkPointMapTemp;
            machineMannedId = machineMannedIdTemp;
        } finally {
            Long e = System.currentTimeMillis();
            log.info("加载数据完成，耗时:{} ms", e - s);
        }
    }

    @Override
    @PostConstruct
    @Scheduled(cron = "30/59 * * * * ?")
    public void reloadMachineStateData() {
        Long s = System.currentTimeMillis();
        try {
            Map<Integer, MachineStatus> machineStatusMapTemp = new HashMap<>();
            /**车辆id：车辆状态*/
            List<MachineStatus> machineStatuses = machineStatusService.getMachineStatusAll();
            for (MachineStatus machineStatus : machineStatuses) {
                try {
                    machineStatusMapTemp.put(machineStatus.getMachineId(), machineStatus);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
            machineStatusMap = machineStatusMapTemp;
        } finally {
            Long e = System.currentTimeMillis();
            log.info("加载machineStatus完成，耗时:{} ms", e - s);
        }
    }

    @Override
    @Scheduled(cron = "0 1/30 * * * ?")
    public void batteryData() {
        Long s = System.currentTimeMillis();

        redisService.del(RedisConstant.PUSH_BMS_Machine + null);
        redisService.del(RedisConstant.PUSH_BMS_Battery + null);
        redisService.del(RedisConstant.PUSH_BMS_Model + null);

        /**初始化电量bms数据*/
        List<Machine> machineList = machineDao.getAll();
        List<String> machineNOs = machineList.stream().map(Machine::getMachineNO).collect(Collectors.toList());

        List<Battery> batteryList = batteryService.getAll();
        if (CollUtil.isNotEmpty(batteryList)) {
            List<Integer> batteryMachineIds = batteryList.stream().map(Battery::getMachineId).collect(Collectors.toList());
            List<Machine> batteryMachines = machineService.getByMachineIds(batteryMachineIds);
            List<String> batteryMachineNOs = batteryMachines.stream().map(Machine::getMachineNO).collect(Collectors.toList());

            /**不存在车辆编号*/
            List<String> del = ListUtil.getSameString(machineNOs, batteryMachineNOs);
            for (String machine : del) {
                redisService.del(RedisConstant.PUSH_BMS_Machine + machine);
            }

            for (Battery battery : batteryList) {
                if (battery.getUserCode() != null) {
                    redisService.add(RedisConstant.PUSH_BMS_Machine + machineUserNO.get(battery.getUserCode()), battery.getBatteryNO());
                }
                redisService.add(RedisConstant.PUSH_BMS_Battery + battery.getBatteryNO(), JSONObject.toJSONString(battery));
            }
        }

        List<BatteryModelChart> batteryModelCharts = batteryModelChartService.getAll();
        for (BatteryModelChart batteryModelChart : batteryModelCharts) {
            redisService.add(RedisConstant.PUSH_BMS_Model + batteryModelChart.getBatteryModelId(), JSONObject.toJSONString(batteryModelChart));
        }

        Long e = System.currentTimeMillis();
        log.info("初始化电量bms数据，耗时:{} ms", e - s);
    }


    @Override
    public Integer getMachineId(String machineNo) {
        Integer machineId = machineNoId.get(machineNo);
        if (machineId == null) {
            Machine machine = machineService.getByMachineNO(machineNo);
            if (machine == null) {
                throw new BaseException("Machine.notExist");
            } else {
                machineId = machine.getMachineId();
            }
        }
        return machineId;
    }

    @Override
    public Integer getMachineIdLister(String machineNo) {
        return machineNoId.get(machineNo);
    }

    @Override
    public Integer getId(String machineNo) {
        return machineNoId.get(machineNo);
    }

    @Override
    public Integer getMachineIdUserCode(String userCode) {
        String machineNo = machineUserNO.get(userCode);
        return StrUtil.isBlank(machineNo) ? null : machineNoId.get(machineNo);
    }

    @Override
    public String getMachineNO(String userCode) {
        return machineUserNO.get(userCode);
    }

    @Override
    public Integer getAccountId(String machineNO) {
        Integer machineId = getMachineId(machineNO);
        return machineMap.get(machineId).getAccountId();
    }

    @Override
    public AccountConfig getAccountConfig(Integer accountId) {
        return accountConfigMap.get(accountId);
    }

    @Override
    public WorkOrderConfig getWorkOrderConfig(Integer accountId) {
        return workOrderConfigMap.get(accountId);
    }

    @Override
    public List<Integer> getByMachineIds(List<String> machineNos) {
        List<Integer> machineIds = new LinkedList<>();
        for (String machineNo : machineNos) {
            try {
                machineIds.add(machineNoId.get(machineNo));
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
        return machineIds;
    }

    @Override
    public List<AccountUserWorkConfig> getAccountUserWorkConfigByAccountId(Integer accountId) {
        return accountUserWorkConfigMap.getOrDefault(accountId, Collections.emptyList());
    }

    @Override
    public AccountUserWork getAccountUserWorkByAccountUserId(Integer accountUserId) {
        return accountUserWorkMap.get(accountUserId);
    }

    @Override
    public List<Point> getGeo(Integer accountId) {
        return geoMap.getOrDefault(accountId, Collections.emptyList());
    }

    @Override
    public List<Integer> getAccountIdGeore(Integer accountId) {
        return accountGeoreMap.getOrDefault(accountId, Collections.emptyList());
    }

    @Override
    public List<Point> getGeore(Integer regionId) {
        return georeGionMap.getOrDefault(regionId, Collections.emptyList());
    }

    @Override
    public AddCountFee getAddFee(Integer accountId) {
        return accountFeeMap.get(accountId);
    }


    @Override
    public AccountSmsModel getAccountSmsModel(String accountIdType) {
        return smsModelMap.get(accountIdType);
    }

    @Override
    public String getMachineNo(Integer machineId) {
        String key = null;
        for (String getKey : machineNoId.keySet()) {
            try {
                if (machineNoId.get(getKey).equals(machineId)) {
                    key = getKey;
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
        return key;
    }

    @Override
    public AccountUserLastPos getByAccountUserLastPos(Integer accountUserId) {
        return accountUserLastPosMap.get(accountUserId);
    }

    @Override
    public Map<Integer, AccountUserLastPos> getByUserId(Collection<Integer> accountUserIds) {
        Map<Integer, AccountUserLastPos> map = new HashMap<>();
        for (Integer accountUserId : accountUserIds) {
            if (accountUserLastPosMap.containsKey(accountUserId)) {
                map.put(accountUserId, accountUserLastPosMap.get(accountUserId));
            }
        }
        return map;
    }

    @Override
    public Integer getByGeoMachineId(Integer machineId) {
        return machineIdRegionIdMap.get(machineId);
    }

    @Override
    public List<Integer> getByRegionId(Integer regionId) {
        return regionIdAccountUserIdMap.getOrDefault(regionId, Collections.emptyList());
    }

    @Override
    public AccountUserConfig getByAccountUserId(Integer userId) {
        return accountUserConfigMap.get(userId);
    }

    @Override
    public Integer getParentId(Integer accountId) {
        return accountIdMap.get(accountId);
    }

    @Override
    public MachineStatus getMachineStatus(Integer machineId) {
        return machineStatusMap.get(machineId);
    }

    @Override
    public List<AccountConfig> getAllAccountConfig() {
        Collection<AccountConfig> valueCollection = accountConfigMap.values();
        return new ArrayList<>(valueCollection);
    }

    @Override
    public Machine getMachine(Integer machineId) {
        return machineMap.get(machineId);
    }

    @Override
    public List<Machine> getMachines(List<Integer> machineIds) {
        List<Machine> machineList = new ArrayList<>();
        for (Integer key : machineIds) {
            try {
                machineList.add(machineMap.get(key));
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
        machineList = machineList.stream().filter(Objects::nonNull).collect(Collectors.toList());
        return machineList;
    }

    @Override
    public AccountUser getAccountUser(Integer accountUserId) {
        return accountUserMap.get(accountUserId);
    }

    @Override
    public AccountConfigExt getAccountidExt(String accountExt) {
        return accountConfigExtMap.get(accountExt);
    }

    @Override
    public boolean getParkPointBound(Integer parkPointId) {
        return parkBoundMap.contains(parkPointId);
    }

    @Override
    public boolean getMachineType(Integer machineId) {
        return machineFunctionList.contains(machineId);
    }

    @Override
    public DispatchConfig getDispatch(Integer accoountId) {
        return accountDispatchMap.get(accoountId);
    }

    @Override
    public Integer getBatteryId(String batteryNO) {
        Integer batteryId = batteryIdMap.get(batteryNO);
        if (batteryId == null) {
            batteryId = batteryService.getByNO(batteryNO).getBatteryId();
        }
        return batteryId;
    }

    @Override
    public Integer getBatteryAccountId(String batteryNO) {
        return batteryAccountIdMap.get(batteryNO);
    }

    @Override
    public BatteryModelChart getByIdBatteryModelChart(Integer batteryModelChartId) {
        BatteryModelChart batteryModelChart = batteryModelChartHashMap.get(batteryModelChartId);
        if (batteryModelChart == null) {
            batteryModelChart = batteryModelChartService.getByModelId(batteryModelChartId);
            if (batteryModelChart != null) {
                batteryModelChartHashMap.put(batteryModelChartId, batteryModelChart);
            }
        }
        return batteryModelChart;
    }

    @Override
    public BmsBatch getBmsBatch(Integer bmsBatch) {
        BmsBatch bmsBatchD = bmsBatchHashMap.get(bmsBatch);
        if (bmsBatchD == null) {
            bmsBatchD = bmsBatchService.getBmsBatch(bmsBatch);
        }
        return bmsBatchD;
    }

    @Override
    public Integer getModelId(String batteryNO) {
        Integer modelId = batteryModelIdMap.get(batteryNO);
        if (modelId == null) {
            Battery battery = batteryService.getByNO(batteryNO);
            batteryModelIdMap.put(battery.getBatteryNO(), battery.getBatteryModelId());
            modelId = battery.getBatteryModelId();
        }
        return modelId;
    }

    @Override
    public Integer getRoleConfig(String rokeIdKey) {
        return roleConfigMap.get(rokeIdKey);
    }

    @Override
    public List<Point> getParkList(Integer parkPointId) {
        ParkPoint parkPoint = getParkPoint(parkPointId);
        if (parkPoint != null) {
            return GeoUtil.getPoints(parkPoint.getPoints());
        }
        return new ArrayList<>();
    }

    @Override
    public ParkPoint getParkPoint(Integer parkPointId) {
        ParkPoint parkPoint = integerParkPointMap.get(parkPointId);
        if (parkPoint == null){
            parkPoint = parkPointService.getByParkPointId(parkPointId);
            if (parkPoint.getAllowRange() == -1){
                AccountConfigExt allowRangeConfig = accountConfigExtService.getParamKey(parkPoint.getAccountId(), AccountConfigExtConstant.ALL_PARK_POINT_ALLOW_RANGE);
                if (allowRangeConfig != null){
                    parkPoint.setAllowRange(Integer.valueOf(allowRangeConfig.getParamValue()));
                }else {
                    parkPoint.setAllowRange(20);
                }
            }
        }
        return parkPoint;
    }


    //定时统计管理平台资金数据接口
    @Override
    @Scheduled(cron = "0 8 */1 * * ?")
    public void operationalDataToMain() {
        Map<Integer, Map<String, Object>> operationalDataToMainMapTemp = new HashMap<>();

        LogUtil.info("定时统计管理平台资金数据接口 定时任务！");
        long t1 = System.currentTimeMillis();

        /**获取所有品牌id,区域id*/
        Map<Integer, List<Integer>> brandIdAccountIdS = accountService.getStageBrandIdAccountIdS();

        /**
         * 请求管理端接口
         */
        for (Integer brandId : brandIdAccountIdS.keySet()) {
            Map<String, Object> operationalDataToMain = accountDayStatApi.operationalData(new OperationalDataDTO(DateUtil.parse("2018-01-01 00:00:00"), DateUtil.parse(DateTimeUtil.getNowTimeYMD() + " 23:59:59"), brandId, StringUtil.getListString(brandIdAccountIdS.get(brandId))));
            //Map<String, Object> operationalDataToMain = UQHttpManager.operationalDataToMain(brandId, StringUtil.getListString(brandIdAccountIdS.get(brandId)), "2018-01-01 00:00:00", DateTimeUtil.getNowTimeYMD() + " 23:59:59");
            if (operationalDataToMain == null) {
                throw new BaseException("System.error");
            } else {
                operationalDataToMainMapTemp.put(brandId, operationalDataToMain);
            }
        }

        operationalDataToMainMap = operationalDataToMainMapTemp;
        long t2 = System.currentTimeMillis();
        LogUtil.info("定时统计管理平台资金数据接口 定时任务时间" + (t2 - t1) + "ms");
    }

    @Override
    public Map<String, Object> getoperationalDataToMainMapTemp(Integer brandId) {
        return operationalDataToMainMap.get(brandId);
    }

    @Override
    public Integer getMannedId(Integer machineId) {
        return machineMannedId.get(machineId);
    }

    @Override
    public Integer getBatteryIdNoDb(String batteryNO) {
        return batteryIdMap.get(batteryNO);
    }
}

